package diamond.day03;

import java.util.concurrent.locks.ReentrantLock;

public class ThreadTest {
    public static void main(String[] args) {
        Window w = new Window();
        Thread t1 = new Thread(w);
        Thread t2 = new Thread(w);
        Thread t3 = new Thread(w);
        t1.start();
        t2.start();
        t3.start();
    }
}

class Window implements Runnable{
    private int ticket = 100;
    private ReentrantLock reentrantLock = new ReentrantLock(); // 1、实例化ReentrantLock
    public void run() {
        while(true){
            try{
                reentrantLock.lock(); // 2、上锁
                if(ticket>0){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {

                    }
                    System.out.println(Thread.currentThread().getName() + ":卖票，票号为：" + ticket);
                    ticket--;
                }else {
                    break;
                }
            }finally {
                reentrantLock.unlock(); // 3、解锁
            }
        }
    }
}
